<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Adapter
 *
 * @author marvin
 */
namespace Engine\Auth;
class Adapter implements \Zend_Auth_Adapter_Interface {

    /**
     *
     * @var string
     */
    private $_identityCol = 'email';

    /**
     *
     * @var string
     */
    private $_credentialCol = 'password';

    /**
     *
     * @var string
     */
    private $_tableName = 'Entities\Profile';

    /**
     *
     * @var string
     */
    private $_email;

    /**
     *
     * @var string
     */
    private $_password;

    /**
     *
     * @var object
     */
    private $_user;

    /**
     *
     * @param string $email
     * @param string $password
     */
    public function  __construct($email, $password) {
        $this->_email       = (string) $email;
        $this->_password    = (string) $password;
    }

    public function setCredential($credentialCol) {
        $this->_credentialCol = (string) $credentialCol;
        return $this;
    }

    public function setIdentity($identityCol) {
        $this->_identityCol = (string) $identityCol;
        return $this;
    }

    public function setTableName($tableName) {
        $this->_tableName = (string) $tableName;
        return $this;
    }

    public function  authenticate() {
        
        $authManager = new \Managers\Auth($this->_identityCol, $this->_credentialCol, $this->_tableName);
        try {
           
            $this->_user = $authManager->authenticate($this->_email, $this->_password);
            return $this->createResult(\Zend_Auth_Result::SUCCESS);
        }
        catch (\Exception $e) {
            switch ($e->getCode()) {
                case \Managers\Auth::NOT_FOUND :
                    return $this->createResult(\Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, array('not found'));
                    break;
                case \Managers\Auth::WRONG_PASSWORD :
                    return $this->createResult(\Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, array('password invalid'));
                    break;
                case \Managers\Auth::FAILURE :
                    return $this->createResult(\Zend_Auth_Result::FAILURE_UNCATEGORIZED, array('failure'));
                    break;
                case \Managers\Auth::IDENTITY_AMBIGUOUS :
                    return $this->createResult(\Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS, array('AMBIGUOUS'));
                    break;
            }

        }
    }

    private function createResult($code, $messages = array()) {
        return new \Zend_Auth_Result($code, $this->_user, $messages);
    }

}